import React, { Component } from 'react'
import { Spring, animated } from 'react-spring'  //导入spring动画库
import FilterTitle from '../FilterTitle'
import FilterPicker from '../FilterPicker'
import FilterMore from '../FilterMore'
import { API } from '../../../../utils/api' //导入自定义的axios

import styles from './index.module.css'
/**
 * 标题高亮状态
 */
const titleSelectedStatus = {
  area: false,
  mode: false,
  price: false,
  more: false
}
// 默认选中的状态
const selectedValues = {
  area: ["area", null],
  mode: ["null"],
  price: ["null"],
  more: []
};
export default class Filter extends Component {
  state = {
    titleSelectedStatus, //标题高亮
    openType: '',  //展示不同的组件
    filtersData: {}, //获取到的区域信息
    selectedValues  //  // 筛选默认选中的状态值
  }
  componentDidMount() {
    //获取到body
    this.htmlBody = document.body;
    this.getFilterData()
  }
  componentWillUnmount() {
    this.setState = () => false;   //解决刷新bug
  }

  //获取区域信息
  async getFilterData() {
    let { value } = JSON.parse(localStorage.getItem('hkzf_city'))
    const res = await API.get(`houses/condition?id=${value}`)
    this.setState({
      filtersData: res.data.body
    })

  }
  // 封装渲染FilterPicker组件的方法
  renderFilterPicker() {
    let { openType, filtersData: { area, subway, rentType, price }, selectedValues } = this.state
    if (openType !== "area" && openType !== "mode" && openType !== "price") {
      return null
    }
    // 拼接数据
    let data = [];
    // pickerView显示的列数
    let cols = 3
    let defaultValue = selectedValues[openType];
    switch (openType) {
      case 'area':
        // 区域数据
        data = [area, subway];
        cols = 3
        break;
      case 'mode':
        // 方式数据
        data = rentType;
        cols = 1
        break;
      case "price":
        // 租金数据
        data = price;
        cols = 1
        break;
      default:
        break;
    }

    return <FilterPicker key={openType} onCancel={this.onCancel} onSave={this.onSave} data={data} cols={cols} type={openType} defaultValue={defaultValue} />;
  }
  //封装renderFilterMore方法，渲染FilterMore组件
  renderFilterMore() {
    const { openType, filtersData: { roomType, oriented, floor, characteristic } } = this.state
    let defaultValue = this.state.selectedValues.more  //拿到默认选中值
    const data = { roomType, oriented, floor, characteristic }
    if (openType !== 'more') {
      return null
    }
    // {/* 最后一个菜单对应的内容： */ }
    return <FilterMore data={data} type={openType} onSave={this.onSave} defaultValue={defaultValue} onCancel={this.onCancel} />;

  }
  //title点击高亮效果 注意箭头函数
  onTitleClick = type => {
    this.htmlBody.className = 'body-overflow-hidden'    //解决弹出框后还可以滚动房屋数据列表的BUG
    // 获取到两个状态：标题选中状态对象和筛选条件的选中值对象
    const { titleSelectedStatus, selectedValues } = this.state;
    // 根据当前标题选中状态对象，获取到一个新的标题选中状态对象
    const newTitleSelectedStatus = { ...titleSelectedStatus };
    // 使用Object.keys()，遍历标题选中状态对象
    Object.keys(titleSelectedStatus).forEach(key => {
      // key表示数组中每一项
      if (key === type) {
        // 当前标题
        newTitleSelectedStatus[type] = true
        return
      }
      // 其他标题
      const selectedVal = selectedValues[key]
      if
        (key === "area" && (selectedVal.length !== 2 ||
          selectedVal[0] !== "area"
        )) {
        newTitleSelectedStatus[key] = true;
      } else if (key === "mode" && selectedVal[0] !== "null") {
        newTitleSelectedStatus[key] = true;
      } else if (key === "price" && selectedVal[0] !== "null") {
        newTitleSelectedStatus[key] = true;
      } else if (key === "more" && selectedVal.length !== 0) {
        // 更多选择
        newTitleSelectedStatus[key] = true;
      } else {
        newTitleSelectedStatus[key] = false;
      }
    })

    this.setState({
      titleSelectedStatus: newTitleSelectedStatus,
      openType: type
    });
  };
  //取消按钮事件
  onCancel = (type) => {
    this.htmlBody.className = ''   //解决弹出框后还可以滚动房屋数据列表的BUG
    // 获取到两个状态：标题选中状态对象和筛选条件的选中值对象
    const { titleSelectedStatus, selectedValues } = this.state;
    // 根据当前标题选中状态对象，获取到一个新的标题选中状态对象
    const newTitleSelectedStatus = { ...titleSelectedStatus };
    // 其他标题
    const selectedVal = selectedValues[type]
    if
      (type === "area" && (selectedVal.length !== 2 ||
        selectedVal[0] !== "area"
      )) {
      newTitleSelectedStatus[type] = true;
    } else if (type === "mode" && selectedVal[0] !== "null") {
      newTitleSelectedStatus[type] = true;
    } else if (type === "price" && selectedVal[0] !== "null") {
      newTitleSelectedStatus[type] = true;
    } else if (type === "more" && selectedVal.length !== 0) {
      // 更多选择
      newTitleSelectedStatus[type] = true;
    } else {
      newTitleSelectedStatus[type] = false;
    }
    this.setState({
      // 隐藏组件
      openType: '',
      // 高亮的title
      titleSelectedStatus: newTitleSelectedStatus
    })
  }
  //确定按钮事件
  onSave = (type, value) => {
    this.htmlBody.className = ''   //解决弹出框后还可以滚动房屋数据列表的BUG
    // 获取到两个状态：标题选中状态对象和筛选条件的选中值对象
    const { titleSelectedStatus } = this.state;
    // 根据当前标题选中状态对象，获取到一个新的标题选中状态对象
    const newTitleSelectedStatus = { ...titleSelectedStatus };
    // 其他标题
    const selectedVal = value
    if
      (type === "area" && (selectedVal.length !== 2 ||
        selectedVal[0] !== "area"
      )) {
      newTitleSelectedStatus[type] = true;
    } else if (type === "mode" && selectedVal[0] !== "null") {
      newTitleSelectedStatus[type] = true;
    } else if (type === "price" && selectedVal[0] !== "null") {
      newTitleSelectedStatus[type] = true;
    } else if (type === "more" && selectedVal.length !== 0) {
      // 更多选择
      newTitleSelectedStatus[type] = true;
    } else {
      newTitleSelectedStatus[type] = false;
    }



    //发起请求 // 组拼数据格式
    let newSectedValues = {
      ...this.state.selectedValues,
      [type]: value
    }
    const { area, mode, price, more } = newSectedValues;
    // 筛选条件数据
    const filters = {};
    // 区域
    const areaKey = area[0];
    let areaValue = "null";
    if (area.length === 3) {
      areaValue = area[2] !== "null" ? area[2] : area[1]
    }
    filters[areaKey] = areaValue;
    // 方式和租金
    filters.mode = mode[0];
    filters.price = price[0];
    // more
    filters.more = more.join(",");

    // 将筛选条件数据filters传递给父组件HouseList
    this.props.onFilter(filters);
    this.setState({
      // 隐藏组件
      openType: '',
      //高亮的
      titleSelectedStatus: newTitleSelectedStatus,
      // 添加上次选中的选项
      selectedValues: newSectedValues
    })
  }
  //渲染遮罩层
  renderMask() {
    const { openType } = this.state
    const isHide = openType === 'more' || openType === ''  //不是前三项其中一个
    return (
      <Spring from={{ opacity: 0 }} to={{ opacity: isHide ? 0 : 1 }}>
        {props => {
          // 说明遮罩层已经完成动画效果，隐藏了
          if (props.opacity === 0) {
            return null
          }
          return (<animated.div style={props} className={styles.mask} onClick={() => this.onCancel(openType)} />)
        }}
      </Spring>
    )

  }
  render() {
    const { titleSelectedStatus } = this.state
    return (
      <div className={styles.root}>
        {/* 前三个菜单的遮罩层 */}

        {this.renderMask()}
        <div className={styles.content}>
          {/* 标题栏 */}
          <FilterTitle titleSelectedStatus={titleSelectedStatus} onClick={this.onTitleClick} />
          {/* 前三个菜单对应的内容： */}
          {this.renderFilterPicker()}
          {/* 筛选组件 */}
          {this.renderFilterMore()}
        </div>
      </div>
    )
  }
}
